<?php

namespace app\common\service\face;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\facade\Log;

class CompareFaces
{
    public static function verify($imageData): bool
    {
        AlibabaCloud::accessKeyClient(env('face.AccessKey_ID'), env('face.AccessKey_Secret'))
            ->regionId('cn-shanghai')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('facebody')
                ->scheme('https') // https | http
                ->version('2019-12-30')
                ->action('CompareFace')
                ->method('POST')
                ->host('facebody.cn-shanghai.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-shanghai",
                        // 质量分阈值,小于该阈值则失败
                        'QualityScoreThreshold' => 80,
                        'ImageDataA' => $imageData[0],
                        'ImageDataB' => $imageData[1],
                    ],
                ])
                ->request();
            $code = $result->getStatusCode();
            if ($code !== 200) {
                return false;
            }
            $res = $result->toArray();
            Log::error('face verify:'.json_encode($res, JSON_UNESCAPED_UNICODE));
            if ($res['Data']['Confidence'] < 80) {
                return false;
            }
            return true;
        } catch (ClientException $exception) {
            $log['msg'] = $exception->getMessage();
            Log::error('face verify clientEx:'.json_encode($log, JSON_UNESCAPED_UNICODE));
            return false;
        } catch (ServerException $exception) {
            $log = [
                'msg' => $exception->getMessage(),
                'code' => $exception->getErrorCode(),
                'requestId' => $exception->getRequestId(),
                'errorMsg' => $exception->getErrorMessage(),
            ];
            Log::error('face verify serverEx:'.json_encode($log, JSON_UNESCAPED_UNICODE));
            return false;
        }
    }
}